/**
 * @author Aaron
 * @createTime 9:40 2022/5/17
 **/
package db_main

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"longmen/server/config/global"
	"longmen/server/pkg/common/api_models"
	utils2 "longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
)

/**
 * @author Aaron
 * @description DAO层 GetTaskListParam
 * @createTime 9:40 2022/5/17
 **/
func GetTaskListParam(param map[string]interface{}, page int, size int) ([]*api_models.Task, error) {
	if size > 20 {
		size = 20
	}
	var o []*api_models.Task
	err := mysql.Condition(mysql.GetRTable(&models_main.Task{}), param, "", "weight DESC", page, size).Where("status", 0).Find(&o).Error
	if err != nil {
		return nil, fmt.Errorf("%s%s", utils2.Convert2(), err.Error())
	}
	return o, nil
}

/**
 * @author Aaron
 * @description DAO层 GetTaskById
 * @createTime 10:43 2022/5/19
 **/
func GetTaskById(id uint8) (*api_models.TaskById, error) {
	fName := "GetTaskById"
	o := new(api_models.TaskById)
	err := mysql.GetRTable(&models_main.Task{}).
		Where("status = 0 AND id = ? ", id).
		Find(o).
		Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		return nil, fmt.Errorf("%s%s", utils2.Convert(fName), err.Error())
	}
	return o, nil
}

func GetTaskListByIds(ids []uint8) ([]*api_models.Task, error) {
	var o []*api_models.Task

	err := global.GetR().
		Raw(fmt.Sprintf("SELECT * FROM db_task WHERE id in %s", utils2.QueryUint8Slice2Str(ids))).
		Find(&o).
		Error
	if err != nil {
		return nil, fmt.Errorf("%s%s", utils2.Convert2(), err.Error())
	}
	return o, nil
}

func GetTaskByType(typ uint8) ([]api_models.TaskById, error) {
	fName := "GetTaskByType"
	o := make([]api_models.TaskById, 0)
	err := mysql.GetRTable(&models_main.Task{}).
		Where("status = 0 AND type = ? ", typ).
		Find(&o).
		Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		return nil, fmt.Errorf("%s%s", utils2.Convert(fName), err.Error())
	}
	return o, nil
}
